package com.cheboohui.iqs.taiping.direct;

import org.apache.http.entity.StringEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.methods.HttpPost;
import com.cheboohui.iqs.http.tool.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import java.io.IOException;

/**
 * 调用太平https接口
 * 
 * @author xielonghai
 *
 */
public class TPPost {

	/**
	 * logger:日志工具.
	 */
	private static Log log = LogFactory.getLog(TPPost.class);

	/**
	 * 接口调用方法
	 * 
	 * @param url
	 *            https访问路径
	 * @param param
	 *            xml请求参数
	 * @return
	 */
	public static String postTP(String url, String param) {
		log.info("请求访问太平直连接口开始...url:" + url);
		log.info("请求访问太平直连接口开始...xml:" + param);
		System.setProperty("jsse.enableSNIExtension", "false");
		CloseableHttpClient httpClient = HttpClient.createSSLClientDefault();
		HttpClientContext httpContext = HttpClientContext.create();
		StringEntity entity = new StringEntity(param, "UTF-8");

		entity.setContentEncoding("UTF-8");

		entity.setContentType("text/xml");

		HttpPost httpPost = new HttpPost(url);

		httpPost.setEntity(entity);
		RequestConfig requestconfing = RequestConfig.custom().setSocketTimeout(1000 * 60).setConnectTimeout(1000 * 60)
				.build();
		httpPost.setConfig(requestconfing);
		CloseableHttpResponse response = null;
		try {
			byte[] signBytes;
			String respEncode = Base64.encode(param.getBytes(PublicNew.defaultCharset));
			signBytes = PublicNew.sign(respEncode.replace("\n", "").getBytes(),
					Base64.decode(PublicNew.getPrivateKey()), PublicNew.algorithm);
			String respSign = Base64.encode(signBytes, Integer.MAX_VALUE);
			httpPost.setHeader("TP-SIGN", respSign);

			response = httpClient.execute(httpPost, httpContext);
			String result = EntityUtils.toString(response.getEntity());
			log.info("请求访问太平直连接口成功...url:" + url);
			return result;
		} catch (Exception e) {
			log.error("请求访问太平直连接口异常:" + e + "...url:" + url);
			return null;
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				log.error("请求访问太平直连接口关闭response异常:" + e + "...url:" + url);
				e.printStackTrace();
			}
		}
	}
}
